// pages/giftSel/giftgiftSel.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit: 10,
    page: 1,
    total_page: 0,
    items: [], //列表
    hasMore: true,
    total_num: 0, //选择提货商品总数
    addressCol: true,
    isLoadData: false, //是否已加载酒柜数据
  },

  onLoad: function () {
    this.setData({
      items: [],
      page: 1,
      total_page: 0,
      total_num: 0,
      hasMore: true,
      addressCol: true
    })
    this.wineList();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
 
    this.addressList()
  },

  //页面上拉触底
  onReachBottom: function (e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function () {
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.wineList();
  },

  //酒柜列表
  wineList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit,
        status: 1
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          resultList = that.doData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
            if (itemData.length >= 1) {
              //有数据
            } else {
              //无数据
            }
          } else {
            var itemData = that.data.items.concat(resultList)
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            total_page: totalPage,
            items: itemData,
            isLoadData: true
          });

        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        that.setData({
          isLoadData: true
        });
        wx.hideLoading();
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //处理数据
  doData: function (list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      var item = {
        id: list[i].id,
        images: list[i].image,
        name: list[i].gname,
        price: list[i].current_price,
        num: list[i].num,
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
      }
      newList.push(item)
    }
    return newList;
  },

  //提交
  submit: function () {
    var total_num = this.data.total_num;
    if (total_num >= 1) {
      this.setData({
        addressCol: false
      })
    } else {
      util.showError("请选择商品");
    }
  },

  //隐藏地址
  hiddenAddress: function () {
    var that = this;
    that.setData({
      addressCol: true
    })
  },
  //增加
  addNum: function (e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num < info.num) {
      that.total_num(1)
      info.current_num = (info.current_num + 1)
      var items = that.data.items
      items[i] = info;
      that.setData({
        items: items
      })
    }

  },
  //减少
  minusNum: function (e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num >= 1) {
      that.total_num(2)
      info.current_num = (info.current_num - 1)
      var items = that.data.items
      items[i] = info;
      that.setData({
        items: items
      })
    }
  },

  //总数量
  total_num: function (type = 1) {
    var total_num = this.data.total_num;
    this.setData({
      total_num: (type == 1) ? (total_num + 1) : (total_num - 1)
    })
  },

  //地址列表
  addressList: function () {
    var params = new Object()
    var that = this;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'address/list',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var addressList = res.data.data.address_list;
          for (var i = 0; i < addressList.length; i++) {
            if (addressList[i].is_default == 1) {
              var addressId = addressList[i].aid
            }
          }
          that.setData({
            addressId: addressId,
            address: addressList
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //添加新地址
  addAddress: function () {
    wx.navigateTo({
      url: '../addAddress/addAddress'
    })
  },

  //修改地址
  editorAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/addAddress/addAddress?aid=' + id
    })
  },
  //删除地址
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认删除该地址?',
      confirmColor: "#e51927",
      success: function (res) {
        if (res.confirm) {
          api.POST({
            params: { aid: id },
            url: app.globalData.base_url + 'address/del',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                util.showStatus("删除成功")
                that.addressList();
              }
            },
            fail: function (fail) {
              util.showError("登录失败，请检查网络");

            }
          })
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    })
  },

  //选择地址
  radioChange: function (e) {
    var id = e.detail.value
    this.setData({
      addressId: e.detail.value
    })
  },

  //确认配送
  confirm: function (e) {
    var that = this;
    var items = that.data.items;
    var params = new Object()
    params.record = [];
    var list = [];
    for (var i = 0; i < items.length; i++) {
      if (items[i].current_num > 0) {
        var box = {};
        box.sku_code = items[i].sku_code
        box.num = items[i].current_num
        list.push(box);
      }
    }
    params.record = JSON.stringify(list)
    params.use_type = 2;
    params.aid = that.data.addressId;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'winecabinet/use',
      success: function (res) {
        if (res.data.code) {
          util.showError(res.data.message)
        } else {
          wx.showModal({
            title: '提示',
            content: '提交成功',
            cancelText: '查看订单',
            confirmText: '返回酒柜',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '../wine/wine'
                })
              } else if (res.cancel) {
                wx.redirectTo({
                  url: '../myOrder/myOrder'
                })
              }
            }
          })
        }
      }, fail: function (fail) {
        util.showError("请检查网络");
      }
    })
  },


})